﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using HaterAide.Interfaces;
using HaterAide.SQL.DataClasses;

#endregion

namespace HaterAide.Mappings
{
    /// <summary>
    /// Used to map a class to the database
    /// </summary>
    /// <typeparam name="T">The type of the object to map</typeparam>
    /// <typeparam name="D">The database config type of the database</typeparam>
    public class ClassMapping<T,D> : BaseMapping, IClassMap<T>, IAttributeMap
    {
        #region Private Functions

        /// <summary>
        /// Sets up the mapping
        /// </summary>
        private void Setup()
        {
            if (Properties == null)
            {
                Properties = new List<Attribute>();
            }
            if (AssociatedTable == null)
            {
                AssociatedTable = new Table(typeof(T).Name + "_", null);
            }
            if (IDProperties == null)
            {
                IDProperties = new List<Attribute>();
            }
            if(string.IsNullOrEmpty(DatabaseName))
            {
                DatabaseName = typeof(D).Name;
            }
        }
        
        /// <summary>
        /// Adds an attribute to the list
        /// </summary>
        /// <param name="Property">Attribute to add</param>
        /// <param name="expression">The expression defining the property</param>
        private void AddAttribute(Attribute Property, Expression<Func<T, object>> Expression,string PropertyName="")
        {
            Setup();
            Property.Name = Utilities.Reflection.Reflection.GetPropertyName<T>(Expression);
            Property.Type = Utilities.Reflection.Reflection.GetPropertyType<T>(Property.Name);
            Property.DerivedFieldName = "_" + Property.Name + "Derived";
            Properties.Add(Property);
            string ColumnName = Property.Name + "_";
            if (!string.IsNullOrEmpty(PropertyName))
            {
                ColumnName = PropertyName;
            }
            if (Property.MappingType == AttributeType.Reference 
                && (!Utilities.Reflection.Reflection.IsIEnumerable(Property.Type)
                    ||Utilities.Reflection.Reflection.IsOfType(Property.Type, typeof(string))))
            {
                Column TempColumn = new Column(ColumnName, SQL.Helpers.GlobalFunctions.GetSQLType(Property.Type).ToString(),
                    Property.Length, true, false, false, false, false, "", "", "", AssociatedTable);
                Property.AssociatedTable = TempColumn;
                AssociatedTable.Columns.Add(TempColumn);
            }
            else if (Property.MappingType == AttributeType.ID)
            {
                Column TempColumn = new Column(ColumnName, SQL.Helpers.GlobalFunctions.GetSQLType(Property.Type).ToString(),
                    Property.Length, false, Property.AutoIncrement, true, true, false, "", "", "", AssociatedTable);
                Property.AssociatedTable = TempColumn;
                AssociatedTable.Columns.Add(TempColumn);
                IDProperties.Add(Property);
            }
        }

        #endregion

        #region IClassMap Members

        public void ID(Expression<Func<T, object>> expression, bool AutoIncrement,string PropertyName="")
        {
            Attribute _ID = new Attribute();
            _ID.MappingType = AttributeType.ID;
            _ID.AutoIncrement = AutoIncrement;
            _ID.Cascade = false;
            AddAttribute(_ID, expression, PropertyName);
        }

        public void ID(Expression<Func<T, object>> expression, int Length, string PropertyName = "")
        {
            Attribute _ID = new Attribute();
            _ID.MappingType = AttributeType.ID;
            _ID.AutoIncrement = false;
            _ID.Cascade = false;
            _ID.Length = Length;
            AddAttribute(_ID, expression, PropertyName);
        }

        public void Reference(Expression<Func<T, object>> expression, string PropertyName = "")
        {
            Attribute _ID = new Attribute();
            _ID.MappingType = AttributeType.Reference;
            _ID.Length = 0;
            _ID.Cascade = false;
            AddAttribute(_ID, expression, PropertyName);
        }

        public void Reference(Expression<Func<T, object>> expression, int Length, string PropertyName = "")
        {
            Attribute _ID = new Attribute();
            _ID.MappingType = AttributeType.Reference;
            _ID.Length = Length;
            _ID.Cascade = false;
            AddAttribute(_ID, expression, PropertyName);
        }

        public void Map(Expression<Func<T, object>> expression, bool Cascade)
        {
            Attribute _ID = new Attribute();
            _ID.MappingType = AttributeType.Map;
            _ID.Cascade = Cascade;
            AddAttribute(_ID, expression);
        }

        public void ManyToOne(Expression<Func<T, object>> expression, string MappedProperty, bool Cascade)
        {
            Attribute _ID = new Attribute();
            _ID.MappingType = AttributeType.ManyToOne;
            _ID.MappedTable = MappedProperty;
            _ID.Cascade = Cascade;
            AddAttribute(_ID, expression);
        }

        public void ManyToMany(Expression<Func<T, object>> expression, string MappedProperty, bool Cascade)
        {
            Attribute _ID = new Attribute();
            _ID.MappingType = AttributeType.ManyToMany;
            _ID.MappedTable = MappedProperty;
            _ID.Cascade = Cascade;
            AddAttribute(_ID, expression);
        }

        public void Table(string TableName)
        {
            Setup();
            this.AssociatedTable.Name = TableName;
        }

        #endregion

        #region IAttributeMap Members

        public List<Attribute> Properties { get; set; }

        public List<Attribute> IDProperties { get; set; }

        public Table AssociatedTable { get; set; }

        public void SetupStructure(Utilities.SQL.DataClasses.Database Database)
        {
            foreach (Attribute Property in Properties)
            {
                if (Property.MappingType == AttributeType.Reference && Utilities.Reflection.Reflection.IsIEnumerable(Property.Type)
                    && !Utilities.Reflection.Reflection.IsOfType(Property.Type, typeof(string)))
                {
                    Property.MappedTable = AssociatedTable.Name + Property.Name;//typeof(T).Name+"_"+Property.Name;
                    Table TempTable = new Table(Property.MappedTable, Database);
                    Property.AssociatedTable = TempTable;

                    Column TempColumn = new Column("ID_0", SqlDbType.Int.ToString(), 0, false, true, true, true, false, "", "", "", TempTable);
                    TempTable.Columns.Add(TempColumn);

                    TempColumn = new Column(Property.Name, SQL.Helpers.GlobalFunctions.GetSQLType(Property.Type.GetGenericArguments()[0]).ToString(), Property.Length, false, false, false, false, false, "", "", "", TempTable);
                    TempTable.Columns.Add(TempColumn);

                    //Table MappedTable = AssociatedTable;//(Table)Database[AssociatedTable.Name];
                    Column MappedPrimaryKey = (Column)AssociatedTable.PrimaryKeys[0];
                    TempColumn = new Column(AssociatedTable.Name + MappedPrimaryKey.Name, MappedPrimaryKey.DataType.ToString(), MappedPrimaryKey.Length, false, false, false, false, false, AssociatedTable.Name, MappedPrimaryKey.Name, "", TempTable);
                    TempTable.Columns.Add(TempColumn);

                    Database.Tables.Add(TempTable);
                }
                else if (Property.MappingType == AttributeType.Map)
                {
                    if (((BaseMapping)this.MappingManager.ClassMappings[Property.Type]).DatabaseName == DatabaseName)
                    {
                        Table MappedTable = (Table)this.MappingManager.ClassMappings[Property.Type].AssociatedTable;
                        Column MappedPrimaryKey = (Column)MappedTable.PrimaryKeys[0];
                        Column TempColumn = new Column(MappedTable.Name + Property.Name + "_ID",
                                MappedPrimaryKey.DataType.ToString(), MappedPrimaryKey.Length,
                                true, false, false, false, false, MappedTable.Name, MappedPrimaryKey.Name, "",
                                AssociatedTable);
                        Property.AssociatedTable = TempColumn;
                        AssociatedTable.Columns.Add(TempColumn);
                    }
                    else
                    {
                        Table MappedTable = (Table)this.MappingManager.ClassMappings[Property.Type].AssociatedTable;
                        Column MappedPrimaryKey = (Column)MappedTable.PrimaryKeys[0];
                        Column TempColumn = new Column(MappedTable.Name + Property.Name + "_ID",
                                MappedPrimaryKey.DataType.ToString(), MappedPrimaryKey.Length,
                                true, false, false, false, false, "", "", "",
                                AssociatedTable);
                        Property.AssociatedTable = TempColumn;
                        AssociatedTable.Columns.Add(TempColumn);
                    }
                }
                else if (Property.MappingType == AttributeType.ManyToOne || Property.MappingType == AttributeType.ManyToMany)
                {
                    Property.AssociatedTable = null;
                    foreach (Table Table in Database.Tables)
                    {
                        if (Table.Name == Property.MappedTable)
                        {
                            Property.AssociatedTable = Table;
                            break;
                        }
                    }
                    if (Property.AssociatedTable == null)
                    {
                        Table TempTable = new Table(Property.MappedTable, Database);
                        Property.AssociatedTable = TempTable;
                        Column TempColumn = new Column("ID_", SqlDbType.Int.ToString(), 0, false, true, true, true, false, "", "", "", TempTable);
                        TempTable.Columns.Add(TempColumn);
                        if (Utilities.Reflection.Reflection.IsIEnumerable(Property.Type))
                        {
                            Type MappedType = Property.Type.GetGenericArguments()[0];
                            Table MappedTable = this.MappingManager.ClassMappings[MappedType].AssociatedTable;//(Table)Database[MappedType.Name + "_"];
                            Column MappedPrimaryKey = (Column)MappedTable.PrimaryKeys[0];
                            if (MappedTable.ParentDatabase == AssociatedTable.ParentDatabase)
                            {
                                TempColumn = new Column(MappedTable.Name + MappedPrimaryKey.Name,
                                    MappedPrimaryKey.DataType.ToString(), MappedPrimaryKey.Length,
                                    false, false, false, false, false, MappedTable.Name, MappedPrimaryKey.Name, "",
                                    TempTable);
                            }
                            else
                            {
                                TempColumn = new Column(MappedTable.Name + MappedPrimaryKey.Name,
                                    MappedPrimaryKey.DataType.ToString(), MappedPrimaryKey.Length,
                                    false, false, false, false, false, "", "", "",
                                    TempTable);
                            }
                            TempTable.Columns.Add(TempColumn);
                        }
                        else
                        {
                            Type MappedType = Property.Type;
                            Table MappedTable = this.MappingManager.ClassMappings[MappedType].AssociatedTable; //(Table)Database[MappedType.Name + "_"];
                            Column MappedPrimaryKey = (Column)MappedTable.PrimaryKeys[0];
                            if (MappedTable.ParentDatabase == AssociatedTable.ParentDatabase)
                            {
                                TempColumn = new Column(MappedTable.Name + MappedPrimaryKey.Name,
                                    MappedPrimaryKey.DataType.ToString(), MappedPrimaryKey.Length,
                                    false, false, false, false, false, MappedTable.Name, MappedPrimaryKey.Name, "",
                                    TempTable);
                            }
                            else
                            {
                                TempColumn = new Column(MappedTable.Name + MappedPrimaryKey.Name,
                                    MappedPrimaryKey.DataType.ToString(), MappedPrimaryKey.Length,
                                    false, false, false, false, false, "", "", "",
                                    TempTable);
                            }
                            TempTable.Columns.Add(TempColumn);
                        }
                        Column PrimaryKey = (Column)AssociatedTable.PrimaryKeys[0];
                        Column TempColumn2 = new Column(AssociatedTable.Name + PrimaryKey.Name,
                            PrimaryKey.DataType.ToString(), PrimaryKey.Length,
                            false, false, false, false, false, AssociatedTable.Name,
                            PrimaryKey.Name, "", TempTable);
                        TempTable.Columns.Add(TempColumn2);
                        Database.Tables.Add(TempTable);
                    }
                }
            }
        }

        #endregion
    }
}